package com.woniuxy.closer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.io.Files;
import com.woniuxy.closer.ResponseEntity;
import com.woniuxy.closer.entity.Contacts;
import com.woniuxy.closer.entity.ContactsV;
import com.woniuxy.closer.service.ContactsService;
import com.woniuxy.closer.service.ContactsVService;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 李玉桃
 * @since 2022-07-20
 */
@RestController
@RequestMapping("/closer/contacts")
public class ContactsController {

    @Autowired
    ContactsService contactsService;
    @Autowired
    ContactsVService contactsVService;

    @GetMapping("{id}")
    public ResponseEntity findById(@PathVariable int id) {
        return new ResponseEntity(contactsService.getById(id));
    }

    @PostMapping("")
    public ResponseEntity save(@RequestBody Contacts contacts) {
        System.out.println(contacts);
        boolean flag = contactsService.saveOrUpdate(contacts);


        if (flag) {
            return ResponseEntity.SUCCESS;
        } else {
            return ResponseEntity.ERROR;
        }
    }

    @DeleteMapping("")
    public ResponseEntity delete(@RequestBody int id) {
        boolean flag = contactsService.removeById(id);
        if (flag) {
            return ResponseEntity.SUCCESS;
        } else {
            return ResponseEntity.ERROR;
        }
    }

    //map里面的KEY要安装数据库里的字段
    @PostMapping("find")
    public ResponseEntity findByCondition(@RequestBody Map map) {
        QueryWrapper<ContactsV> contactsWrapper = new QueryWrapper<>();
        for (Object o : map.entrySet()) {
            Map.Entry<String,Object> next = (Map.Entry) o;
            if (!next.getValue().equals("")) {
//                map.remove(next.getKey());
                contactsWrapper.like((String) next.getKey(), next.getValue());
            }
        }
        return new ResponseEntity(contactsVService.list(contactsWrapper));

    }

    @PostMapping("export")
    public ResponseEntity export(@RequestBody Map map) {
        try {
            return contactsVService.export(map);
        } catch (IllegalAccessException e) {
            System.out.println("这里有问题");
        }
        return null;
    }


}

